from fastapi import APIRouter, HTTPException
from schemas.image import ImageGenerateRequest
from services.image_service import ImageService
from schemas.base import create_response
from db.crud.image import get_user_images, clear_user_images, save_image_record

router = APIRouter(prefix="/image", tags=["image"])
service = ImageService()

@router.post("")
async def generate_image(request: ImageGenerateRequest):
    try:
        result = await service.generate_image(request.description)
        # 保存图片生成记录
        await save_image_record(request.userId, request.description, result["imageUrl"])
        return await create_response(200, "图片生成成功", result)
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 500,
                "message": f"图片生成失败: {str(e)}"
            }
        )

@router.get("/{userId}")
async def get_image_history(userId: str):
    try:
        images = await get_user_images(userId)
        return await create_response(200, "获取图片记录成功", images)
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 500,
                "message": f"获取图片记录失败: {str(e)}"
            }
        )

@router.delete("/{userId}")
async def clear_image_history(userId: str):
    try:
        await clear_user_images(userId)
        return await create_response(200, "清空图片记录成功", None)
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 500,
                "message": f"清空图片记录失败: {str(e)}"
            }
        )

